import 'package:cmd_myapp_demo/components/my_app.dart';
import 'package:cmd_myapp_demo/components/my_home_page.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp(child: _EventNotificationDemo()));
}

class _EventDemo extends StatelessWidget {
  const _EventDemo({super.key});

  @override
  Widget build(BuildContext context) {
    return const MyHomePage(
      title: Text("Listener 原生指针事件"),
      child: _ListenerPage(),
    );
  }
}

class _ListenerPage extends StatefulWidget {
  const _ListenerPage({super.key});

  @override
  _ListenerPageState createState() => _ListenerPageState();
}

class _ListenerPageState extends State<_ListenerPage> {
  String _opName = "未检测到操作";

  void _showEventText(String text) {
    setState(() {
      _opName = text;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      // 监听
      child: Listener(
        child: Container(
          alignment: Alignment.center,
          color: Colors.blue,
          width: 240.0,
          height: 120.0,
          child: Text(
            _opName,
            style: const TextStyle(color: Colors.white),
          ),
        ),
        onPointerDown: (PointerDownEvent event) => _showEventText("手指按下"),
        onPointerMove: (PointerMoveEvent event) => _showEventText("手指移动"),
        onPointerUp: (PointerUpEvent event) => _showEventText("手指抬起"),
        onPointerCancel: (PointerCancelEvent event) => _showEventText("手指取消"),
      ),
    );
  }
}

// 忽略事件 IgnorePoint
class _EventIgnoreDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MyHomePage(
      title: const Text("忽略事件"),
      child: _PointerEventIgnorePage(),
    );
  }
}

class _PointerEventIgnorePage extends StatefulWidget {
  @override
  _PointerEventIgnorePageState createState() => _PointerEventIgnorePageState();
}

class _PointerEventIgnorePageState extends State<_PointerEventIgnorePage> {
  bool _ignore = false;

  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      child: Column(
        children: <Widget>[
          Switch(
            value: _ignore,
            onChanged: (value) {
              setState(() {
                _ignore = value;
              });
            },
          ),
          GestureDetector(
            onTap: () => debugPrint("GestureDetector Clicked"),
            child: IgnorePointer(
              ignoring: _ignore,
              child: ElevatedButton(
                onPressed: () => debugPrint("IgnorePointer Clicked!"),
                child: const Text("IgnorePointer"),
              ),
            ),
          ),
          GestureDetector(
            onTap: () => debugPrint("GestureDetector Clicked"),
            child: AbsorbPointer(
              absorbing: _ignore,
              child: ElevatedButton(
                onPressed: () => debugPrint("AbsorbPointer Clicked"),
                child: const Text("AbsorbPointer"),
              ),
            ),
          )
        ],
      ),
    );
  }
}

// 手势识别
class _EventDetectorDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MyHomePage(
      title: const Text("手势识别"),
      child: _GestureDetectorPage(),
    );
  }
}

class _GestureDetectorPage extends StatefulWidget {
  @override
  _GestureDetectorPageState createState() => _GestureDetectorPageState();
}

class _GestureDetectorPageState extends State<_GestureDetectorPage> {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        GestureDetector(
          onTap: () => debugPrint("你点击了: ♥"),
          child: Container(
            padding: const EdgeInsets.all(12.0),
            decoration: BoxDecoration(
                color: Theme.of(context).primaryColor,
                borderRadius: BorderRadius.circular(2.0)),
            child: const Text(
              "点击♥",
              style: TextStyle(color: Colors.white),
            ),
          ),
        )
      ],
    );
  }
}

// 拖曳、缩放效果
class _DragDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MyHomePage(
      title: const Text("拖拽效果"),
      child: _DragPage(),
    );
  }
}

class _DragPage extends StatefulWidget {
  @override
  _DragPageState createState() => _DragPageState();
}

// 涉及到手势竞争: 水平移动 ？ 垂直移动
class _DragPageState extends State<_DragPage> {
  double _top = 0.0;
  double _left = 0.0;

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        Positioned(
          top: _top,
          left: _left,
          child: GestureDetector(
            // 垂直移动
            onVerticalDragUpdate: (DragUpdateDetails e) {
              setState(() {
                _top += e.delta.dy;
              });
              debugPrint("垂直胜出");
            },
            // 水平移动
            onHorizontalDragUpdate: (DragUpdateDetails e) {
              setState(() {
                _left += e.delta.dx;
              });
              debugPrint("水平胜出！");
            },
            // 按下
            onTap: () => debugPrint("按下"),
            // 松开
            onTapUp: (e) {
              debugPrint("松开");
            },
            // 水平移动结束
            onHorizontalDragEnd: (e) {
              debugPrint("水平移动结束");
            },
            // 垂直移动结束
            onVerticalDragEnd: (e) {
              debugPrint("垂直移动结束");
            },
            child: Container(
              width: 200.0,
              height: 200.0,
              color: Colors.blue,
            ),
          ),
        )
      ],
    );
  }
}

// 缩放效果
class _ScaleDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MyHomePage(title: const Text("缩放效果"), child: _ScalePage());
  }
}

class _ScalePage extends StatefulWidget {
  @override
  _ScalePageState createState() => _ScalePageState();
}

class _ScalePageState extends State<_ScalePage> {
  double _width = 200.0;
  double _height = 200.0;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        GestureDetector(
          child: Container(
            alignment: Alignment.center,
            child: ElevatedButton(
              onPressed: () => setState(() {
                _width = 200.0;
                _height = 200.0;
              }),
              child: const Text("恢复初始大小"),
            ),
          )
        ),
        GestureDetector(
          // 缩放事件
          onScaleUpdate: (e) {
            setState(() {
              double scaleRate = e.scale;
              _width = 200 * scaleRate.clamp(.5, 1.5);
              _height = 200 * scaleRate.clamp(.5, 1.5);
              debugPrint("宽度: $_width, 高度: $_height");
            });
          },
          child: Container(
            alignment: Alignment.center,
            margin: const EdgeInsets.only(top: 50.0),
            width: _width,
            height: _height,
            color: Colors.blue,
            child: const Text("双指缩放试试", style: TextStyle(color: Colors.white),),
          ),
        )
      ],
    );
  }
}

// 手势识别器
class _GestureRecognizerDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MyHomePage(title: const Text("手势识别-单词本"), child: _GestureRecognizerPage());
  }
}

class _GestureRecognizerPage extends StatefulWidget {
  @override
  _GestureRecognizerState createState() => _GestureRecognizerState();
}

class _GestureRecognizerState extends State<_GestureRecognizerPage> {

  final TapGestureRecognizer _tapGestureRecognizer = TapGestureRecognizer();

  @override
  void dispose() {
    _tapGestureRecognizer.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Text.rich(
            TextSpan(
                children: [
                  const TextSpan(
                      text: "Room is not ",
                      style: TextStyle(fontSize: 25.0)
                  ),
                  TextSpan(
                      text: "build",
                      style: const TextStyle(
                          fontSize: 25.0,
                          fontWeight: FontWeight.bold,
                          color: Colors.blue
                      ),
                      // 加入手势识别器
                      recognizer: _tapGestureRecognizer..onTap = () {
                        ScaffoldMessenger.of(context).showSnackBar(
                            const SnackBar(
                              content: Text("build: 建造"),
                            )
                        );
                      }
                  ),
                  const TextSpan(
                      text: " in one day.",
                      style: TextStyle(fontSize: 25.0)
                  )
                ]
            )
        )
      ],
    );
  }
}

// 事件通知
class _EventNotificationDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MyHomePage(title: const Text("事件通知"), child: _EventNotificationPage());
  }
}

class _EventNotificationPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _EventNotificationState();
}

class _EventNotificationState extends State<_EventNotificationPage> {

  String message = "";

  _onStartScroll(ScrollMetrics metrics) {
    setState(() {
      message = "Scroll Start";
    });
  }

  _onUpdateScroll(ScrollMetrics metrics) {
    setState(() {
      message = "Scroll Update";
    });
  }

  _onEndScroll(ScrollMetrics metrics) {
    setState(() {
      message = "Scroll End";
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Container(
          height: 50.0,
          color: Colors.green,
          child: Center(
            child: Text(message, style: const TextStyle(color: Colors.white),),
          ),
        ),
        Expanded(
          // 接收消息通知
          child: NotificationListener(
            onNotification: (scrollNotification) {
              if (scrollNotification is ScrollStartNotification) {
                _onStartScroll(scrollNotification.metrics);
              } else if (scrollNotification is ScrollUpdateNotification) {
                _onUpdateScroll(scrollNotification.metrics);
              } else if (scrollNotification is ScrollEndNotification) {
                _onEndScroll(scrollNotification.metrics);
              }
              return false;
            },
            child: ListView.builder(
              itemCount: 30,
              itemBuilder: (context, index) {
                return ListTile(title: Text("Index: ${index + 1}"));
              },
            ),
          ),
        )
      ],
    );
  }
}
